﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;

using ECCIT;
using ECCIT.Data;
using ECCIT.Business.DAL;

using OgilvyOne.UKNow.Common;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

namespace OgilvyOne.UKNow.DAL
{
    public class EventsVideoDAL : UKNowBaseDAL, IDALEventsVideo
    {
        private const string TBL_NAME = "UKNOW_EVENTS_VIDEO";
        private const string COL_LANG_ID = "COL_LANG_ID";
        private const string COL_EVENTS_VIDEO_ID = "COL_EVENTS_VIDEO_ID";
        private const string COL_EVENTS_ID = "COL_EVENTS_ID";
        private const string COL_EVENTS_VIDEO_NAME = "COL_EVENTS_VIDEO_NAME";
        private const string COL_EVENTS_VIDEO_PATH = "COL_EVENTS_VIDEO_PATH";
        private const string COL_EVENTS_VIDEO_EXT = "COL_EVENTS_VIDEO_EXT";
        private const string COL_EVENTS_VIDEO_TYPE = "COL_EVENTS_VIDEO_TYPE";
        private const string COL_EVENTS_VIDEO_DESC = "COL_EVENTS_VIDEO_DESC";
        private const string COL_EVENTS_VIDEO_TAG = "COL_EVENTS_VIDEO_TAG";
        private const string COL_EVENTS_VIDEO_STATE = "COL_EVENTS_VIDEO_STATE";
        private const string COL_EVENTS_VIDEO_IMG_PATH = "COL_EVENTS_VIDEO_IMG_PATH";
        private const string COL_EVENTS_VIDEO_ORDER = "COL_EVENTS_VIDEO_ORDER";
        private const string COL_EVENTS_VIDEO_RECO = "COL_EVENTS_VIDEO_RECO";
        private const string COL_EVENTS_VIDEO_INSERT_TIME = "COL_EVENTS_VIDEO_INSERT_TIME";
        private const string COL_EVENTS_VIDEO_UPDATE_TIME = "COL_EVENTS_VIDEO_UPDATE_TIME";

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(EventsVideoModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_ID, DataType.Int)); } }
        public IField EventsID { get { return FieldFactory.Create(ModelType, "EventsID", ColumnFactory.CreateColumn(COL_EVENTS_ID, DataType.Int)); } }
        public IField Name { get { return FieldFactory.Create(ModelType, "Name", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_NAME, DataType.String, 200)); } }
        public IField Path { get { return FieldFactory.Create(ModelType, "Path", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_PATH, DataType.String, 200)); } }
        public IField Extension { get { return FieldFactory.Create(ModelType, "Extension", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_EXT, DataType.String, 20)); } }
        public IField Type { get { return FieldFactory.Create(ModelType, "Type", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_TYPE, DataType.Int)); } }
        public IField Description { get { return FieldFactory.Create(ModelType, "Description", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_DESC, DataType.String, 500)); } }
        public IField Tag { get { return FieldFactory.Create(ModelType, "Tag", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_TAG, DataType.String, 200)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_STATE, DataType.Int)); } }
        public IField ImagePath { get { return FieldFactory.Create(ModelType, "ImagePath", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_IMG_PATH, DataType.String, 200)); } }
        public IField Order { get { return FieldFactory.Create(ModelType, "Order", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_ORDER, DataType.Int)); } }
        public IField IsRecommendation { get { return FieldFactory.Create(ModelType, "IsRecommendation", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_RECO, DataType.Bit)); } }
        public IField InsertedTime { get { return FieldFactory.Create(ModelType, "InsertedTime", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_INSERT_TIME, DataType.DateTime)); } }
        public IField UpdatedTime { get { return FieldFactory.Create(ModelType, "UpdatedTime", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_UPDATE_TIME, DataType.DateTime)); } }

        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Extension, Type, Description, Tag, State, ImagePath, Order, IsRecommendation, InsertedTime, UpdatedTime }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        public override IField[] UpdateFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Extension, Type, Description, Tag, State, ImagePath, Order, IsRecommendation, UpdatedTime }; } }

        public EventsVideoDAL() { }

        public EventsVideoDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        private void SetForeignKeyModel(EventsVideoModel model)
        {
            if (model == null) return;
            model.FileType = (model.Type==3) ? 3 : 2;
            model.ThumbnailImagePath = model.ImagePath;
            model.Events = new EventsDAL(this.Language.LanguageType).GetEventsModelByID(model.EventsID);
        }

        #region IDALEventsVideo Members

        public EventsVideoModel GetEventsVideoModelByID(int? id)
        {
            EventsVideoModel model = (EventsVideoModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            SetForeignKeyModel(model);
            return model;
        }

        public IList<EventsVideoModel> GetAllEventsVideoModels(int? eventsID)
        {
            IDataParameter[] parms = DBHelper.GetDataParameters(new IField[] { EventsID, LanguageID });
            parms[0].Value = eventsID;
            parms[1].Value = (int)this.Language.LanguageType;

            string whereClause = "WHERE " + COL_EVENTS_ID + "=#" + COL_EVENTS_ID + " AND " + COL_LANG_ID + "=#" + COL_LANG_ID;
            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc)), parms).List.Cast<EventsVideoModel>().ToList();
            foreach (EventsVideoModel model in models)
                SetForeignKeyModel(model);

            return models;
        }
        public IList<EventsVideoModel> GetKeywordEventsVideoModels(string keyword)
        {


            string whereClause = String.Format("where COL_EVENTS_VIDEO_TAG like '%{0}%' and COL_EVENTS_VIDEO_STATE={1}", keyword, 1);
            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsVideoModel>().ToList();

            return models;
            //IDataParameter[] parms = DBHelper.GetDataParameters(new IField[] { EventsID, LanguageID });
            //parms[0].Value = keyword;
            //parms[1].Value = (int)this.Language.LanguageType;

            //string whereClause =String.Format( "where col_events_video_tga like '%{0}%' and col_events_state={1}",keyword,1);
            //IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc)), parms).List.Cast<EventsVideoModel>().ToList();
            //foreach (EventsVideoModel model in models)
            //    SetForeignKeyModel(model);

            //return models;
        }

        public IList<EventsVideoModel> GetPublishedEventsVideoModels(int? eventsID)
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_ID, eventsID, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();

            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsVideoModel>().ToList();
            foreach (EventsVideoModel model in models)
                SetForeignKeyModel(model);
            return models;
        }

        public int GetTotalCountByEventsID(int? eventsID)
        {
            string cmd = string.Format("select count({0}) from {1} where {2}={3} and {4}={5} and {6}={7}",
                COL_EVENTS_VIDEO_ID, TBL_NAME, COL_LANG_ID, (int)this.Language.LanguageType, COL_EVENTS_ID, eventsID, COL_EVENTS_VIDEO_STATE, 1);

            object obj = DBHelper.ExecuteScalar(cmd);
            return (int)obj;
        }

        public ResultInfo Save(EventsVideoModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_EVENTS_VIDEO_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    //modelInfo.State = 0;    // 强制将视频状态置为未发布
                    modelInfo.InsertedTime = DateTime.Now;
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "视频数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存视频数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });

                    trans.Commit();
                    result.Result = true;
                    result.Message = "视频数据删除成功！";
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = string.Format("删除视频数据时发生异常。异常信息：{0}", ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }

        public ResultInfo DeleteByEventsID(IDbTransaction trans, int? eventsID)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                string whereClause = string.Format("where {0}={1} and {2}={3}", COL_LANG_ID, (int)this.Language.LanguageType, COL_EVENTS_ID, eventsID);
                Delete(trans, whereClause);
                result.Result = true;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Success);
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Exception, ex);
            }

            return result;
        }

        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_EVENTS_VIDEO_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "视频发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("发布视频时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_EVENTS_VIDEO_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "视频取消发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("取消发布视频时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        #endregion
    }
}
